<template>
    <div :class="className" :style="{height:height,width:width}" />
  </template>
  
  <script>
  import echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'
  
      

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '90%'
      },
      height: {
        type: String,
        default: '600px'
      },
      scatterData: { type: Array, default: Array },
    },
    data() {
      return {
        chart: null,
        scatterDataCopy:[]
      }
    },
    mounted() {
       
      this.$nextTick(() => {
        this.initChart()
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
       const rawData = this.scatterData;
        // 定义区域颜色
        const areaColors = [
            { name: '高登录高解锁', color: '#2f9e44', range: [[0.8, 1.0], [0.8, 1.0]] },
            { name: '高登录中解锁', color: '#a3cf62', range: [[0.8, 1.0], [0.5, 0.8]] },
            { name: '高登录低解锁', color: '#ffd43b', range: [[0.8, 1.0], [0.0, 0.5]] },
            { name: '中登录高解锁', color: '#74c0fc', range: [[0.5, 0.8], [0.8, 1.0]] },
            { name: '中登录中解锁', color: '#b197fc', range: [[0.5, 0.8], [0.5, 0.8]] },
            { name: '中登录低解锁', color: '#ffc078', range: [[0.5, 0.8], [0.0, 0.5]] },
            { name: '低登录高解锁', color: '#4dabf7', range: [[0.0, 0.5], [0.8, 1.0]] },
            { name: '低登录中解锁', color: '#9775fa', range: [[0.0, 0.5], [0.5, 0.8]] },
            { name: '低登录低解锁', color: '#ff8787', range: [[0.0, 0.5], [0.0, 0.5]] }
        ];

        // 处理数据并添加轻微偏移
        const processedData = rawData.map((item, index) => {
            const offset = (index % 10) * 0.002;
            const direction = Math.random() > 0.5 ? 1 : -1;
            const adjustedLoginRate = item.LoginRate + (offset * direction);
            const adjustedUnlockRate = item.UnlockRate + (offset * direction);

            let areaColor = '#ccc';
            let areaName = '其他';

            for (const area of areaColors) {
                const [loginRange, unlockRange] = area.range;
                if (item.LoginRate >= loginRange[0] && item.LoginRate <= loginRange[1] &&
                    item.UnlockRate >= unlockRange[0] && item.UnlockRate <= unlockRange[1]) {
                    areaColor = area.color;
                    areaName = area.name;
                    break;
                }
            }

            return {
                name: item.UserCompanyName,
                value: [adjustedLoginRate, adjustedUnlockRate, item.UserNum],
                originalValue: [item.LoginRate, item.UnlockRate],
                loginUserNum: item.LoginUserNum,
                unlockUserNum: item.UnlockUserNum,
                userNum: item.UserNum,
                itemStyle: { color: areaColor },
                areaName: areaName
            };
        });

        // 按原始坐标分组
        const coordinateGroups = {};
        processedData.forEach(item => {
            const key = `${item.originalValue[0]}_${item.originalValue[1]}`;
            if (!coordinateGroups[key]) {
                coordinateGroups[key] = {
                    loginRate: item.originalValue[0],
                    unlockRate: item.originalValue[1],
                    companies: []
                };
            }
            coordinateGroups[key].companies.push(item);
        });
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption({
            backgroundColor: '#ffffff',
            tooltip: {
                trigger: 'item',
                position:function(point,params,dom,rect,size){
                    // return [point[0], point[1]-50]
                    // point 是鼠标位置，格式：[x, y]
                    // rect 是提示框在屏幕中的位置信息
                    // size 是图表的大小信息
                    // 根据需求调整返回的位置
                    // return [point[0] - 50, point[1]]; // 例如，向左偏移50px
                },
                formatter: function(params) {
                    const originalKey = `${params.data.originalValue[0]}_${params.data.originalValue[1]}`;
                    const group = coordinateGroups[originalKey];

                    let html = `
                        <div class="tooltip-header">
                            <div>坐标点: 登录率 ${(group.loginRate * 100).toFixed(2)}%, 解锁率 ${(group.unlockRate * 100).toFixed(2)}%</div>
                            <div>公司数量: ${group.companies.length}家 | 区域: <span style="color:${params.color}">${params.data.areaName}</span></div>
                        </div>
                        <div class="tooltip-content">
                            <div class="company-list">
                    `;

                    group.companies.forEach(company => {
                        html += `
                            <div class="company-item">
                                <div class="company-name">${company.name}</div>
                                <div class="company-details">
                                    用户: ${company.userNum} | 登录: ${company.loginUserNum} | 解锁: ${company.unlockUserNum}
                                </div>
                            </div>
                        `;
                    });

                    html += `</div></div>`;
                    return html;
                },
                backgroundColor: 'rgba(255,255,255,0.98)',
                borderColor: '#ddd',
                borderWidth: 1,
                textStyle: {
                    color: '#333',
                    fontSize: 13
                },
                extraCssText: `
                    box-shadow: 0 0 15px rgba(0,0,0,0.1);
                    padding: 15px;
                    width: 350px;
                    max-width: 80vw;
                    pointer-events: auto;
                    user-select: text;
                    -webkit-user-select: text;
                `,
                enterable: true
            },
            legend: {
                data: areaColors.map(area => area.name),
                right: 10,
                top: 20
            },
            grid: {
                left: '3%',
                right: '7%',
                bottom: '10%',
                top: '15%',
                containLabel: true
            },
            xAxis: {
                name: '登录率',
                type: 'value',
                min: 0,
                max: 1.05,
                axisLabel: {
                    formatter: '{value}%',
                    color: '#409EFF',
                    fontSize: 14

                },
                nameTextStyle:{
                    color: '#409EFF',
                    fontSize: 14
                }
            },
            yAxis: {
                name: '解锁率',
                type: 'value',
                min: 0,
                max: 1.05,
                axisLabel: {
                    formatter: '{value}%',
                    color: '#409EFF',
                    fontSize: 14

                },
                nameTextStyle:{
                    color: '#409EFF',
                    fontSize: 14

                }
            },
            series: [{
                type: 'scatter',
                symbolSize: function(data) {
                    return Math.max(10, Math.min(40, data[2] * 2));
                },
                data: processedData,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        })
      }
    }
  }
  </script>
     <style>
    
     /* 修复工具提示样式 */
     .echarts-tooltip {
         pointer-events: auto !important;
         user-select: text !important;
         -webkit-user-select: text !important;
     }
     .tooltip-content {
         max-height: 200px;
         overflow-y: auto;
         padding-right: 10px;
         z-index: 999999;
     }
     .tooltip-header {
         font-weight: bold;
         margin-bottom: 8px;
         padding: 25px;
         border-bottom: 1px solid #eee;
         background-color: #eee;
     }
     .company-list {
         margin-top: 8px;
     }
     .company-item {
         margin-bottom: 8px;
         padding-bottom: 8px;
         border-bottom: 1px dashed #eee;
     }
     .company-name {
         font-weight: bold;
         margin-bottom: 3px;
     }
     .company-details {
         font-size: 12px;
         color: #666;
     }
     /* 自定义滚动条 */
     .tooltip-content::-webkit-scrollbar {
         width: 6px;
     }
     .tooltip-content::-webkit-scrollbar-track {
         background: #f1f1f1;
         border-radius: 3px;
     }
     .tooltip-content::-webkit-scrollbar-thumb {
         background: #888;
         border-radius: 3px;
     }
 </style>